<?php

class Adept_Dispatcher_Route {
  
  protected $baseUrl = '';
  protected $controller = '';
  protected $pattern = null;
  protected $params = array();

  public function __construct($pattern = '', $controller = '', $params = array(), $baseUrl = '') {
  	$this->pattern = $pattern;
  	$this->controller = $controller;
  	$this->params = $params;
  	$this->baseUrl = $baseUrl;
  }
  
  public function apply($request) {
    if (!$this->check($request)) {
      return false;
    }
    $path = $this->getNormalizedPath($request);
    $matches = $this->matchParams($path);
    foreach ($this->params as $key => $param) {
      for ($i = 0; $i < count($matches); $i++) {
        $param = str_replace('$' . $i, $matches[$i], $param);
      }
      $request->setParameter($key, $param);
    }
  } 
  
  private function getNormalizedPath($request) {
    $url = $request->getUrl();
    $path = "/" . implode("/", $url->getPathElements()); 
    return $path;
  }
  
  public function check(Adept_Request_Http $request) {
    $path = $this->getNormalizedPath($request);
  	if (preg_match("~^{$this->pattern}$~", $path, $matches)) {
  	  return true;
  	} else {
  	  return false;
  	}
  }
  
  protected function matchParams($urlString) {
  	if (preg_match("~^{$this->pattern}$~", $urlString, $matches)) {
  	  return $matches;
  	} else {
  	  return false;
  	}
  }
  
  public function getController() {
    return $this->controller;
  }
  
  public function setController($controller) {
    $this->controller = $controller;
  }
  
  public function getPattern() {
    return $this->pattern;
  }
  
  public function setPattern($pattern) {
    $this->pattern = $pattern;
  }
  
  public function getBaseUrl() {
    return $this->baseUrl;
  }
  
  public function setBaseUrl($baseUrl) {
    $this->baseUrl = $baseUrl;
  }
  
}